package com.example.onlineanswer.controller;

import com.example.onlineanswer.common.result.Result;
import com.example.onlineanswer.model.entity.Question;
import com.example.onlineanswer.service.ContestService;
import com.example.onlineanswer.service.QuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 实时竞赛控制器
 */
@RestController
@RequestMapping("/api/contests/realtime")
@RequiredArgsConstructor
public class ContestRealTimeController {

    private final ContestService contestService;
    private final QuestionService questionService;

    /**
     * 手动启动竞赛（测试用）
     */
    @PostMapping("/{contestId}/start")
    public Result<Boolean> startContest(@PathVariable Long contestId) {
        boolean result = contestService.startContest(contestId);
        return Result.success(result);
    }

    /**
     * 手动结束竞赛（测试用）
     */
    @PostMapping("/{contestId}/end")
    public Result<Boolean> endContest(@PathVariable Long contestId) {
        boolean result = contestService.endContest(contestId);
        return Result.success(result);
    }

    /**
     * 手动切换题目（测试用）
     */
    @PostMapping("/{contestId}/questions/{questionId}/next")
    public Result<Boolean> nextQuestion(@PathVariable Long contestId, @PathVariable Long questionId) {
        boolean result = contestService.updateCurrentQuestionId(contestId, questionId);
        return Result.success(result);
    }
    
    /**
     * 获取并设置竞赛的第一个题目（初始化竞赛）
     */
    @PostMapping("/{contestId}/initialize")
    public Result<Long> initializeContest(@PathVariable Long contestId) {
        // 获取竞赛中的所有题目
        List<Question> questions = questionService.getQuestionsByContestId(contestId);
        if (questions == null || questions.isEmpty()) {
            return Result.error("竞赛没有题目");
        }
        
        // 获取第一个题目
        Question firstQuestion = questions.stream()
                .filter(q -> q.getOrderNum() == 1 || q.getOrderNum() == 0)
                .findFirst()
                .orElse(questions.get(0));
        
        // 设置为当前题目
        boolean result = contestService.updateCurrentQuestionId(contestId, firstQuestion.getId());
        if (!result) {
            return Result.error("设置当前题目失败");
        }
        
        return Result.success(firstQuestion.getId());
    }
} 